package top.healthylife.controller;/*
 *@Author GaoZeXi
 *@Created time 2020/4/18 2:22
 *@Description:
 * Step by Step  and Stand on,  You Are The Best Investment!!!
 */

import com.alibaba.dubbo.config.annotation.Reference;
import com.alibaba.fastjson.JSON;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import redis.clients.jedis.JedisPool;
import top.healthylife.constant.MessageConstant;
import top.healthylife.constant.RedisMessageConstant;
import top.healthylife.domain.Member;
import top.healthylife.entity.Result;
import top.healthylife.service.MemberService;

import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletResponse;
import java.util.Date;
import java.util.Map;

/**
 * @author GaoZeXi
 * 提供会员表相关操作
 */
@RestController
@RequestMapping("/member")
public class MemberController {

    @Reference
    private MemberService memberService;

    @Autowired
    private JedisPool jedisPool;

    /**
     * 提供login方法进行登录检查，处理逻辑为：
     * 1、校验用户输入的短信验证码是否正确，如果验证码错误则登录失败
     * 2、如果验证码正确，则判断当前用户是否为会员，如果不是会员则自动完成会员注册
     * 3、向客户端写入Cookie，内容为用户手机号
     * 4、将会员信息保存到Redis，使用手机号作为key，保存时长为30分钟
     *
     * @return
     */
    @RequestMapping("/login")
    public Result Login(@RequestBody Map map, HttpServletResponse res) {
        String telephone = (String) map.get("telephone");
        String validateCode = (String) map.get("validateCode");
        String validateCodeInRedis = jedisPool.getResource().get(telephone +
                RedisMessageConstant.SENDTYPE_LOGIN);
        if (validateCode != null && validateCodeInRedis != null && validateCode.equals(validateCodeInRedis)) {
            //验证码正确
            //判断当前手机号是否注册
            Member member = memberService.findByTelephone(telephone);
            if (member == null) {
                //未注册,自动注册
                member = new Member();
                member.setRegTime(new Date());
                member.setPhoneNumber(telephone);
                memberService.add(member);
            }
            //向客户端写入Cookie，内容为用户手机号,[目的]跟踪用户
            Cookie cookie = new Cookie("login_member_telephone", telephone);
            //路径
            cookie.setPath("/");
            //有效期 30天
            cookie.setMaxAge(60*60*24*30);
            res.addCookie(cookie);
            //将会员信息保存到Redis, java对象保存在redis中 要序列化成json串
            String json = JSON.toJSON(member).toString();
            jedisPool.getResource().setex(telephone,60*30,json);
            return new Result(true,MessageConstant.LOGIN_SUCCESS);
        } else {
            //验证码错误
            return new Result(false, MessageConstant.VALIDATECODE_ERROR);
        }
    }
}
